#include "../../../common/etcd.hpp"
#include <gflags/gflags.h>
#include <thread>
#include <brpc/server.h>
#include <butil/logging.h>
#include "main.pb.h"

DEFINE_bool(run_mode, false, "程序的运行模式，false-调试； true-发布；");
DEFINE_string(log_file, "", "发布模式下，用于指定日志的输出文件");
DEFINE_int32(log_level, 0, "发布模式下，用于指定日志输出等级");

DEFINE_string(etcd_host, "http://127.0.0.1:2379", "服务注册中心地址");
DEFINE_string(base_service, "/service", "服务监控根目录");
DEFINE_string(instance_name, "/echo/instance", "当前实例名称");
DEFINE_string(access_host, "127.0.0.1:7070", "当前实例的外部访问地址");
DEFINE_int32(listen_port, 7070, "Rpc服务器监听端口");
class EchoServiceImpl : public example::EchoService
{
    public:
    EchoServiceImpl(){}
    ~EchoServiceImpl(){}
    // done: done 由框架创建，递给服务回调，包含了调用服务回调后的后续
    // 动作，包括检查 response 正确性，序列化，打包，发送等逻辑。不管成功失败， 
    // done->Run()必须在请求处理完成后被用户调用一次
    void Echo(google::protobuf::RpcController *controller,
              const ::example::EchoRequest *request,
              ::example::EchoResponse *response,
              ::google::protobuf::Closure *done)
    {
        //RAII的机制释放done
        brpc::ClosureGuard rpc_guard(done);

        std::cout << "收到了消息" << request->message() << std::endl;

        std::string str = request->message() + "---这是响应";
        response->set_message(str);
    }
};

int main()
{
    //将brpc本身的日志信息关闭掉
    logging::LoggingSettings settings;
    settings.logging_dest = logging::LoggingDestination::LOG_TO_NONE;
    logging::InitLogging(settings);

     //创建服务器对象
    brpc::Server server;
    //将服务添加到服务器中
    EchoServiceImpl echo_service;
    int ret = server.AddService(&echo_service,brpc::ServiceOwnership::SERVER_DOESNT_OWN_SERVICE);
    if(ret == -1) {
        std::cout << "添加rpc服务失败\n";
        return -1;
    }

    //启动服务器
    brpc::ServerOptions options;
    //连接空闲超时时间，-1表示
    options.idle_timeout_sec = -1;
    //io线程数量
    options.num_threads = 1;
    ret = server.Start(8080,&options);
    if(ret == -1) {
        std::cout << "启动服务器失败\n";
        return -1;
    }

    //注册服务
    Registry::ptr rclient = std::make_shared<Registry>(FLAGS_etcd_host);
    //注册的时 /service/echo/instance ;;  发现的时候 /service/echo
    rclient->registry(FLAGS_base_service + FLAGS_instance_name, FLAGS_access_host);

    //服务器运行，直到被要求退出
    server.RunUntilAskedToQuit();


    return 0;
}